/**
 * UtilsList.java
 *
 * @author Beatrice Bacelli
 * @author Luca Bedogni
 * @author Silvia Righini
 */
package unibo.lsb.logic;

import java.util.Iterator;
import java.util.List;

/**
 * Some simple utility methods for managing lists
 */
public class UtilsList {

	/**
	 * Returns a string representation of the elements of a list.
	 * 
	 * @param list
	 *            the list to print
	 * @param elementsSeparator
	 *            separator between elements used
	 * @return
	 */
	public static String printList(List<?> list, String elementsSeparator) {
		List<?> l = list;
		String print = "";
		Iterator<?> i = l.iterator();
		while (i.hasNext()) {
			Object o = i.next();
			// formatting of each element depends on the toString of the element
			// itself
			print = print + o.toString() + elementsSeparator;
		}
		return print;
	}

	/**
	 * Returns a string representation of the elements of a list. Elements are
	 * separated with a newline.
	 * 
	 * @param list
	 * @return
	 */
	public static String printList(List<?> list) {
		String elementsSeparator = System.getProperty("line.separator");
		return printList(list, elementsSeparator);
	}

	/**
	 * Checks whether an object is present in a list. Relies on the equals
	 * method.
	 * 
	 * @param o
	 * @param list
	 * @return
	 */
	public static int findInList(Object o, List<?> list) {
		int position = -1;
		boolean found = false;
		Iterator<?> i = list.iterator();

		while (i.hasNext() && !found) {
			position++;
			Object newObj = i.next();
			if (newObj.equals(o)) {
				found = true;
			}
		}
		if (!found) {
			position = -1;
		}
		return position;
	}

}
